﻿using System.Collections.Generic;

namespace HCore
{
    public class ClientProxy
    {
        private readonly int _playerId;
        private readonly string _name;
        private readonly List<TurnData> _sendTurnDatas;
        private readonly List<TurnData> _recTurnDatas;
        private int _recIndex;

        public ClientProxy(int playerId, string name)
        {
            _playerId = playerId;
            _name = name;
            _sendTurnDatas = new List<TurnData>();
            _recTurnDatas = new List<TurnData>();
            _recIndex = 0;
        }

        public string name => _name;

        public int playerId => _playerId;

        public void RecTurnData(TurnData turnData)
        {
            Debug.Assert(turnData.playerId == _playerId);
            _recTurnDatas.Add(turnData);
        }

        public TurnData SendTurnData(int frameRate, int pid)
        {
            frameRate /= 4;
            if (_recTurnDatas.Count - _recIndex > frameRate)
            {
                _recIndex = _recTurnDatas.Count - frameRate;
            }

            TurnData send;
            if (_recIndex < _recTurnDatas.Count)
            {
                send = _recTurnDatas[_recIndex];
                _recIndex++;
            }
            else
            {
                send = new TurnData(_playerId, 0);
                Command command = new EmptyCommand();
                command.playerId = pid;
                send.AddCommand(command);
            }

            _sendTurnDatas.Add(send);

            return send;
        }
    }
}